﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SourceMaster.Util
{
    public static class ExtensionUtil
    {
        public static string Right(this string str, int length)
        {
            if (length < 0)
                throw new ArgumentOutOfRangeException("length");

            if (length == 0 || str == null)
                return string.Empty;

            int len = str.Length;
            if (length >= len)
                return str;
            else
                return str.Substring(len - length, length);
        }

        public static T Clone<T>(this T source)
        {
            if(!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if(Object.ReferenceEquals(source, null))
            {
                //获取一个该类型的默认的值
                return default(T);
            }

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}
